//
//  AmbitusDetailViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/10/30.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "AmbitusDetailViewController.h"
#import "AmbitusDetailModel.h"
#import "AmbitusDetailTestCell.h"
#import "AmbitusDetailImageCell.h"

@interface AmbitusDetailViewController ()<UITableViewDataSource, UITableViewDelegate, MONActivityIndicatorViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *titleImage;
@property (nonatomic, strong) NSMutableArray *ambitusDetaildataArray;
@property (nonatomic, strong) MONActivityIndicatorView *indicatorView;


@end

@implementation AmbitusDetailViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadData" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
     _app = [[AppDelegate alloc] init];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout= UIRectEdgeNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];

    [self addSubView];
     [self setUpData];
  

    [self indicatorView];
    [self addInternetObserver];
}

// 通知网络状态
- (void)addInternetObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithInternet:) name:@"reloadData" object:nil];
}

- (void)reloadDataWithInternet:(NSNotification *)notification
{
    [self setUpData];
}


- (void)setUpData
{
    if ([_app internetReachableOrNot]) {
        [self addAnimation];
    
    NSString *urlString = [NSString stringWithFormat:@"http://api.lanrenzhoumo.com/wh/common/leo_detail?v=2&session_id=000040b65e35981b5ec9fef02a39ff34887c86&leo_id=%ld",self.leo_id];

    NSString *url = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    [request setHTTPMethod:@"GET"];
    self.ambitusDetaildataArray = [NSMutableArray array];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
        } else {
            NSDictionary *tempDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *tempDict2 = [tempDict valueForKey:@"result"];
            NSMutableArray *tempArr = [tempDict2 valueForKey:@"description"];
            for (NSDictionary *dic in tempArr) {
                AmbitusDetailModel *model = [[AmbitusDetailModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.ambitusDetaildataArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self stopLoading];
                [self.tableView reloadData];
            });
        }
    }];
    [dataTask resume];
    } else {
        [self alertController];
    }
}

- (void)alertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的当前网络中断或网络信号差, 请检查网络后重新进入!!" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 加载动画
- (void)addAnimation
{
    _viewV = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth / 2 - 100, kScreenHeight / 2 - 80, 200, 80)];
    _viewV.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
    _viewV.layer.cornerRadius = 10;
    _viewV.layer.masksToBounds = YES;
    [self.view addSubview:_viewV];
    self.indicator = [[DDIndicator alloc] initWithFrame:CGRectMake(_viewV.width / 2 - 20, _viewV.height / 2 - 20 , 40, 40)];
    [_viewV addSubview:self.indicator];
    [self.indicator startAnimating];
    // [self performSelector:@selector(stopLoading:) withObject:self.indicator afterDelay:5];
}

- (void)stopLoading
{
    [_indicator stopAnimating];
    [self.viewV removeFromSuperview];
}

- (void)addSubView
{
    [self setNavigationBar];
    [self addTableView];
}

- (void)setNavigationBar
{
    self.navigationItem.title = @"户外详情";
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backNew.png"] style:(UIBarButtonItemStylePlain) target:self action:@selector(actionLeftButton:)];
   
    self.navigationItem.leftBarButtonItem = leftButton;
}

- (void)actionLeftButton:(UIBarButtonItem *)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)addTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:(UITableViewStylePlain)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.contentInset = UIEdgeInsetsMake(210, 0, 0, 0);
    
    self.titleImage = [[UIImageView alloc] init];
    self.titleImage.contentMode = UIViewContentModeScaleAspectFill;
    self.titleImage.layer.masksToBounds = YES;
    self.titleImage.frame = CGRectMake(0, -210.0f, kScreenWidth, 210);
    [self.titleImage sd_setImageWithURL:[NSURL URLWithString:self.imageUrl] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    [self.tableView addSubview:self.titleImage];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    titleLable.font = [UIFont systemFontOfSize:20];
    titleLable.text = self.titleStr;
    titleLable.textAlignment = NSTextAlignmentCenter;
    titleLable.numberOfLines = 0;
    CGRect newFrame = titleLable.frame;
   newFrame.size.height = [AmbitusDetailViewController cellHeightWithModel:self.titleStr font:20];
    titleLable.frame = newFrame;
    [headerView addSubview:titleLable];
    // 图片
    UIImageView *detailImageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 255) / 2, titleLable.bottom + 10, 255, 50)];
    detailImageView.image = [UIImage imageNamed:@"DetailTitle.png"];
    
    // 图片上的label
    UILabel *imageLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 17, 255, 16)];
    imageLable.text = @"        具       体       详       情";
    imageLable.backgroundColor = [UIColor whiteColor];
    [detailImageView addSubview:imageLable];
    [headerView addSubview:detailImageView];
    
    CGRect newFrame1 = headerView.frame;
    newFrame1.size.height = detailImageView.bottom + 20;
    headerView.frame = newFrame1;
    
    self.tableView.tableHeaderView = headerView;
    [self.view addSubview:self.tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.ambitusDetaildataArray.count > 1) {
        return self.ambitusDetaildataArray.count - 1;
    }
        return self.ambitusDetaildataArray.count ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.ambitusDetaildataArray.count > 0) {
        AmbitusDetailModel *model = self.ambitusDetaildataArray[indexPath.row];
        if ([model.type isEqualToString:@"image"]) {
            static NSString *identifier = @"AmbitusDetailImage";
            AmbitusDetailImageCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[AmbitusDetailImageCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
            }
            cell.model = model;
            return cell;
        } else if ([model.type isEqualToString:@"text"]){
            static NSString *identifier1 = @"AmbitusDetailTest";
            AmbitusDetailTestCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier1];
            if (cell == nil) {
                cell = [[AmbitusDetailTestCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier1];
            }
            cell.model = model;
            return cell;

        }
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AmbitusDetailModel *model = self.ambitusDetaildataArray[indexPath.row];
    if ([model.type isEqualToString:@"image"]) {
        if (model.size.count > 0) {
            NSArray *size = model.size;
            CGFloat scale = [size[0] integerValue] / kScreenWidth;
            CGFloat newHeight = (CGFloat)[size[1] integerValue] / scale;

            return newHeight;
        }
        return 180;
        
    } else if ([model.type isEqualToString:@"text"]) {
       CGFloat newHe = [AmbitusDetailTestCell cellHeightWithModel:model.content font:15];
        
        return newHe;
    } else {
        return 0;
    }
}


+ (CGFloat)cellHeightWithModel:(NSString *)str font:(NSInteger)font
{
    // 计算字符串高度
    // 字号一定与lable相等
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:font] forKey:NSFontAttributeName];
    CGRect lableFrame = [str boundingRectWithSize:CGSizeMake(kScreenWidth , 100000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dic context:nil];
    return lableFrame.size.height;
}

//下拉放大顶部图片
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat f = scrollView.contentOffset.y;
    
    if (f < -210) {
        CGRect newF = self.titleImage.frame;
        newF.origin.y = f;
        newF.size.height = -f;
        self.titleImage.frame = newF;
    }
}

#pragma mark - 添加加载等待动画
- (void)addIndicatorView
{
    _indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.center = self.view.center;
    _indicatorView.delegate = self;
    
    _indicatorView.numberOfCircles = 5; // 圆点个数
    _indicatorView.internalSpacing = 5; // 圆点之间的距离
    _indicatorView.radius = 8; // 圆点半径
    //    _indicatorView.delay = 0;
    
    [self.view addSubview:_indicatorView];
    [_indicatorView startAnimating];
}

#pragma mark - 加载等待动画的代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    switch (index) {
        case 0:
            return [UIColor redColor];
            break;
        case 1:
            return [UIColor magentaColor];
            break;
        case 2:
            return [UIColor orangeColor];
            break;
        case 3:
            return [UIColor purpleColor];
            break;
        default:
            return [UIColor yellowColor];
            break;;
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
